//
//  WordsView.m
//  KidReading
//
//  Created by telen on 15/1/4.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "WordsView.h"
#import "ConstDefine.h"

#define __baseHighLineColer [UIColor colorWithHexString:@"#7E8FDA"]

@interface UIWebView (word)
@property(nonatomic,strong)NSString* web_word;
@end

@implementation UIWebView (word)
ASSOCIATED(web_word, setWeb_word, NSString*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@end

@interface UISegmentedControl (DictArray)
@property(nonatomic,strong)NSArray* dictArr;
@end

@implementation UISegmentedControl (DictArray)
ASSOCIATED(dictArr, setDictArr, NSArray*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@end

@implementation WordsView
{
    BOOL isStrokeSupportFilesOK;
    //
    NSDictionary* tempDict;
    NSString* tempWord;
    NSString* tempPinYin;
    //
    UIView* webWaittingView;
    //
    NSDictionary* wordsDict;
}

@synthesize isInShowing = isTransformWorking;

- (void)setEnBook_Dic:(BOOL)enBook_Dic
{
    _enBook_Dic = enBook_Dic;
    if (enBook_Dic) {
        lable_keyWords.font = [UIFont systemFontOfSize:lable_keyWords.cnFiedWeightHeight*0.8];
        lable_keyWords.textColor = [UIColor blackColor];
        lable_keyWords.text = lable_keyWords.text;
    }else{
        lable_keyWords.font = [UIFont fontWithName:__KaiTiFontName size:lable_keyWords.cnFiedWeightHeight*0.8];
        lable_keyWords.textColor = [UIColor colorWithHexString:@"#7E8FDA"];
        lable_keyWords.text = lable_keyWords.text;
    }
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //将查询字典load到内存中
        NSError* error;
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"getword.bundle/wordsDict"ofType:@"json"];
        NSData *jsondata = [[NSData alloc]initWithContentsOfFile:filePath];
        wordsDict = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingMutableContainers error:&error];
        //
        UIImageView* bgv = [[UIImageView alloc] initWithFrame:self.bounds];
        [self addSubview:bgv];
        UIImage* img = [UIImage imageNamed:@"getWord_bg.png"];
        img = [img stretchableImageWithLeftCapWidth:img.size.width/2 topCapHeight:img.size.height/2];
        bgv.image = img;
        //
        CGFloat ratio_w = [DataProcessing shareSingle].ratio_w;
        CGFloat pod = 6/ratio_w;
        frame.size.width -= pod*2;
        frame.size.height -= pod*2;
        frame.origin.x += pod;
        frame.origin.y += pod;
        UIView* headerView = [[UIView alloc] initWithFrame:frame];
        [self addSubview:headerView];
//        bgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"getWord_bg_rightcorne.png"]];
//        [headerView addSubview:bgv];
//        bgv.center = CGPointMake(headerView.frame.size.width-bgv.frame.size.width/2, bgv.frame.size.height/2);
//        bgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"getWord_bg_leftcorner.png"]];
//        [headerView addSubview:bgv];
        [headerView.layer setCornerRadius:12/ratio_w];
        [headerView.layer setMasksToBounds:YES];
        //
        //
        CGFloat w = frame.size.width;
        CGFloat h = frame.size.height;
        lineHeight_KeyWords = w/15;
        lineHeight_PinyinWords = lineHeight_KeyWords*0.8;
        lineHeight_content = lineHeight_KeyWords*0.75;
        CGFloat pod_h = 20/ratio_w;
        CGFloat pod_w = w/10;
        CGFloat h_functionView = 60/ratio_w;
//        CGFloat pod_tt = w/30;
        CGFloat wh = w/15;
        frame = CGRectMake(0, 0, wh, wh);
        CGPoint pt = CGPointMake(w-pod_w-wh/2, pod_h+wh/2);
//        noteBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"Words_note_able.png" imageOff:@"Words_note_able.png"];
//        [noteBtn setDisAbleImageStr:@"Words_note_unable.png"];
//        noteBtn.center = pt;
//        [noteBtn setDisAble:YES];
//        [self addSubview:noteBtn];
//        //
//        pt = CGPointMake(w-pod_w-wh/2-(wh+pod_tt), pod_h+wh/2);
//        biShunBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"Words_bi_able.png" imageOff:@"Words_bi_able.png"];
//        [biShunBtn setDisAbleImageStr:@"Words_bi_unable.png"];
//        biShunBtn.center = pt;
//        [biShunBtn setDisAble:YES];
//        [self addSubview:biShunBtn];
        //
//        pt = CGPointMake(w-pod_w-wh/2-(wh+pod_tt)*2, pod_h+wh/2);
//        soundBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"" imageOff:@"getWord_btn_speaker_normal_1.png"];
//        [soundBtn setDisAbleImageStr:@""];
//        NSArray* arr = [NSArray arrayWithObjects:[UIImage imageNamed:@"getWord_btn_speaker_normal.png"],[UIImage imageNamed:@"getWord_btn_speaker_normal_1.png"], nil];
//        [soundBtn setAni_UImageArr:arr ani_duration:1 forStatus:YES];
//        soundBtn.center = pt;
//        soundBtn.delegate = self;
//        [soundBtn setDisAble:YES];
//        [self addSubview:soundBtn];
        //
        CGFloat h_word = 60/ratio_w;
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
            h_word *= 1.0;
        }
        frame = CGRectMake(0, 0, w-pod_w*3, h_word);
        pt = CGPointMake(w/2 - pod_w/2, pod_h+wh+lineHeight_KeyWords/2);
        lable_keyWords = [[CNFieldLabel alloc] initWithFrame:frame];
        lable_keyWords.userInteractionEnabled = NO;
//        lable_keyWords.text = @"非常";
        lable_keyWords.text = nil;
        lable_keyWords.delegate = self;
        lable_keyWords.cnFiedWeightHeight = h_word;
        lable_keyWords.font = [UIFont fontWithName:__KaiTiFontName size:lable_keyWords.cnFiedWeightHeight*0.8];
        lable_keyWords.textColor = __baseHighLineColer;
        lable_keyWords.center = pt;
        [self addSubview:lable_keyWords];
        
        //
        CGFloat s_y = pod_h+wh+lineHeight_KeyWords+lineHeight_PinyinWords;
        frame = CGRectMake(pod_w*1.2, s_y, w-pod_w*2, h-s_y-h_functionView);
        UIView* clipView = [[UIView alloc] initWithFrame:frame];
        clipView.clipsToBounds = YES;
        [self addSubview:clipView];
        //
        frame.origin = CGPointZero;
        scrollView = [[UIScrollView alloc] initWithFrame:frame];
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.showsVerticalScrollIndicator = YES;
        scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -4);
        [clipView addSubview:scrollView];
        //
        _webView = [[UIWebView alloc] initWithFrame:frame];
        _webView.mediaPlaybackRequiresUserAction = NO;
        _webView.allowsInlineMediaPlayback = YES;
        _webView.backgroundColor = [UIColor clearColor];
        _webView.delegate = self;
        [clipView addSubview:_webView];
        _webView.hidden = YES;
        //写字
        fieldView = [[CNFieldView alloc] initWithFrame:frame];
        [clipView addSubview:fieldView];
        
        //其他功能面板
        functionView = [self getFunctionView:CGRectMake(pod, clipView.frame.size.height+clipView.frame.origin.y, headerView.frame.size.width, h_functionView)];
        [self addSubview:functionView];
        //判断是否含有i
        if ([ReadBookVOrH_VC currentReadInstance].showInfoDict.count > 0) {
            CGFloat bigger_ratio = ratio_w;
            if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
                bigger_ratio = ratio_w / 1.3;
            }
            UIButton* showInfoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [showInfoBtn addTouchScaleTransitions];
            [showInfoBtn setTitle:@"i" forState:UIControlStateNormal];
            [showInfoBtn setTitleColor:[UIColor colorWithHexString:@"#7E8FDA"] forState:UIControlStateNormal];
            showInfoBtn.layer.cornerRadius = 15 / bigger_ratio;
            showInfoBtn.layer.borderColor = [UIColor colorWithHexString:@"#7E8FDA"].CGColor;
            showInfoBtn.layer.borderWidth = 1;
            showInfoBtn.titleLabel.font = [UIFont boldSystemFontOfSize:25 / bigger_ratio];
            showInfoBtn.alpha = 0.6;
            [showInfoBtn addTarget:self action:@selector(tapShowInfo:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:showInfoBtn];
            [showInfoBtn JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                make.centerY.JRMAS_equalTo(functionView);
                make.height.width.JRMAS_equalTo(30 / bigger_ratio);
                make.left.JRMAS_equalTo(30 / bigger_ratio);
            }];
        }
        
        //
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSelfUndo)];
        [self addGestureRecognizer:tap];
        //
        //创建手势
        UIPanGestureRecognizer *panGR =
        [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didDragged:)];
        //限定操作的触点数
        [panGR setMaximumNumberOfTouches:1];
        [panGR setMinimumNumberOfTouches:1];
        //将手势添加到draggableObj里
        [self addGestureRecognizer:panGR];
        //
        [[WordsDictData shareSingle] setGetWordsDelegate:self];
    }
    return self;
}

- (UIView*)getFunctionView:(CGRect)frame
{
    UIView* view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor clearColor];
    UILabel* line = [[UILabel alloc] initWithFrame:CGRectMake(0,0,frame.size.width,1)];
    line.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.1];
    [view addSubview:line];
    //
    CGFloat ratio_w = [DataProcessing shareSingle].ratio_w;
//    CGSize size = CGSizeMake(106/ratio_w, 30/ratio_w);
//    langBtn = [[StatusButton_2_View alloc] initWithFrame:CGRectMake(frame.size.width-size.width-16/ratio_w,(frame.size.height-size.height)/2.0,size.width,size.height) imageOn:@"btn_change_left.png" imageOff:@"btn_change_right.png"];
//    langBtn.delegate = self;
//    langBtn.hidden = YES;
//    [langBtn setDisAble:NO];
//    NSString* lang = [WordsDictData shareSingle].getDict_Lang;
//    if ([lang isEqualToString:@"cn"]) {
//        [langBtn setButtonStatus:NO];
//    }else{
//        [langBtn setButtonStatus:YES];
//    }
//    [view addSubview:langBtn];
    CGFloat oneItemWidth = 90;
    NSArray* itemsArray = @[@"汉 / En",@"汉 / 汉",@"汉字通"];
    langControl = [[UISegmentedControl alloc] initWithItems:itemsArray];
    [langControl addTarget:self action:@selector(tapLangControlAction:) forControlEvents:UIControlEventValueChanged];
    langControl.selectedSegmentIndex = 0;
    langControl.tintColor = [UIColor colorWithHexString:@"#7E8FDA"];
    UIFont *font = [UIFont boldSystemFontOfSize:16.0f];
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        oneItemWidth = 60;
        font = [UIFont boldSystemFontOfSize:10.0f];
    }
    UIColor *textColor = [UIColor colorWithHexString:@"#7E8FDA"];
    NSDictionary *attributes = @{NSFontAttributeName:font,NSForegroundColorAttributeName:textColor};
    [langControl setTitleTextAttributes:attributes
                               forState:UIControlStateNormal];
    [view addSubview:langControl];
    [langControl JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.center.JRMAS_equalTo(0);
        make.size.JRMAS_equalTo(CGSizeMake(oneItemWidth * itemsArray.count, 30 / ratio_w));
    }];
    NSString* lang = [WordsDictData shareSingle].getDict_Lang;
    if ([lang isEqualToString:@"cn"]) {
        langControl.selectedSegmentIndex = 1;
    }else{
        langControl.selectedSegmentIndex = 0;
    }
    
    //
    return view;
}
//
-(void)tapShowInfo:(UIButton*)button{
    NSDictionary* showInfo = [ReadBookVOrH_VC currentReadInstance].showInfoDict;
    [[WaitingShow shareSingleShow] showString:[DataProcessing chooseLanguageFromCN:showInfo[@"dictNameZh"] andEN:showInfo[@"dictNameEn"]] andAutoHide:YES];
}

- (void)dealloc
{
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
    self.pt_unshowFollowView = nil;
    [[WordsDictData shareSingle] unSetGetWordsDelegate:self];
}

- (BOOL)isStrokeFilesOK
{
    if (isStrokeSupportFilesOK) return isStrokeSupportFilesOK;
    NSString* fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"stroke.db"];
    isStrokeSupportFilesOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
    if (!isStrokeSupportFilesOK) return isStrokeSupportFilesOK;
    fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"fill.db"];
    isStrokeSupportFilesOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
    if (!isStrokeSupportFilesOK) return isStrokeSupportFilesOK;
    fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"strokewave"];
    isStrokeSupportFilesOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
    //
    NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
    if ([@"SG" isEqualToString:countryCode]) {
        fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"sg/stroke.db"];
        isStrokeSupportFilesOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
        if (!isStrokeSupportFilesOK) return isStrokeSupportFilesOK;
        fPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"sg/fill.db"];
        isStrokeSupportFilesOK = [[NSFileManager defaultManager] fileExistsAtPath:fPath];
    }
    //
    return isStrokeSupportFilesOK;
}

- (void)didClickOnWord:(NSString *)text
{
    NSString* selectedTitle = [langControl titleForSegmentAtIndex:langControl.selectedSegmentIndex];
    if ([selectedTitle isEqualToString:@"汉字通"]) {
        if ([wordsDict objectForKey:text]) {
            [self loadWordDictHtmlWithWord:text];
        }else{
            [self loadNoHansHtml];
        }
        return;
    }
    if (fieldView.isShow) {
        if ([text isEqual:fieldView.word]) {
            [fieldView unshow];
        }else{
            [fieldView playWord:text];
        }
    }else{
        fieldView.word = text;
        if([self isStrokeFilesOK] && [DataProcessing onlyChinesWords:text] && text.length == 1){
            [fieldView show];
            //阅读统计
            //[[DBHelper shareInstance] addReadInfo_pageWord:_currentBookId pageIndex:_currentPage_C type:RType_graph word:text];
            [self msgTo_menthed:@"statistical_strokeWords:" refs:@[text] needReturnValue:NO];
        }
    }
    //telen 统计
//    if (fieldView.isShow)[UMSAgent postEvent:@"Page_getword_clk_word" label:@"whenIsShowing"];
//    else [UMSAgent postEvent:@"Page_getword_clk_word" label:@"whenIsUnshow"];
    [self msgTo_menthed:@"statistical_clickOnWord" refs:nil needReturnValue:NO];
}

- (void)didDragged:(UIPanGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateChanged ||
        sender.state == UIGestureRecognizerStateEnded) {
        //注意，这里取得的参照坐标系是该对象的上层View的坐标。
        CGPoint offset = [sender translationInView:self.superview];
        UIView *draggableObj = self;
        //通过计算偏移量来设定draggableObj的新坐标
        CGPoint pt = CGPointMake(draggableObj.center.x + offset.x, draggableObj.center.y + offset.y);
        [draggableObj setCenter:pt];
        //初始化sender中的坐标位置。如果不初始化，移动坐标会一直积累起来。
        [sender setTranslation:CGPointMake(0, 0) inView:self.superview];
        
        //telen 统计
        //if (sender.state == UIGestureRecognizerStateEnded) {
//            [UMSAgent postEvent:@"Page_getword_drag" label:self.bookName];
            //[NSObject msgToClassName:@"UMSAgent" menthed:@"postEvent:label:" refs:@[@"Page_getword_drag",self.bookName] needReturnValue:NO];
        //}
    }
}

- (void)tapSelfUndo{}

- (int)indexForSwitch:(NSArray*)dictArr
{
    BOOL isOnlyChinese = [DataProcessing onlyChinesWords:lable_keyWords.text];
    //判断是否含有汉字通
    NSInteger selectIndex_old = langControl.selectedSegmentIndex;
    NSInteger titleItem = langControl.numberOfSegments;
    CGFloat ratio_w = [DataProcessing shareSingle].ratio_w;
    CGFloat oneItemWidth = 90;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        oneItemWidth = 60;
    }
    BOOL isHasHans = NO;
    for (int i = 0; i < lable_keyWords.text.length; i ++) {
        NSString* oneStr = [lable_keyWords.text substringWithRange:NSMakeRange(i, 1)];
        if ([wordsDict objectForKey:oneStr]) {
            isHasHans = YES;
        }
    }
    NSString* firstLang = [dictArr firstObject][@"type"];
    if ([firstLang isEqualToString:@"kr"]) {
        firstLang = @"cn";
    }
    if (!isHasHans && isOnlyChinese) {
        [lable_keyWords changeTextStyle:FieldLabelStyle_TianZiGe];
        [langControl JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
            make.center.JRMAS_equalTo(0);
            make.size.JRMAS_equalTo(CGSizeMake(oneItemWidth * dictArr.count, 30 / ratio_w));
        }];
        if (titleItem != dictArr.count || ![self isEqualToLastControlSegmentWithDictArr:dictArr]) {
            if ([firstLang isEqualToString:@"en"]) {
                selectIndex_old = 0;
            }else if ([firstLang isEqualToString:@"cn"]){
                selectIndex_old = 1;
            }
            if (dictArr.count == 1) {
                selectIndex_old = 0;
            }
            [[WordsDictData shareSingle] setDict_Lang:firstLang];
            _webView.hidden = YES;
            scrollView.hidden = NO;
        }
    }else if(isHasHans){
        [langControl JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
            make.center.JRMAS_equalTo(0);
            make.size.JRMAS_equalTo(CGSizeMake(oneItemWidth * (dictArr.count + 1), 30 / ratio_w));
        }];
        if (titleItem != dictArr.count + 1 || ![self isEqualToLastControlSegmentWithDictArr:dictArr]) {
            if ([firstLang isEqualToString:@"en"]) {
                selectIndex_old = 0;
            }else if ([firstLang isEqualToString:@"cn"]){
                selectIndex_old = 1;
            }
            if (dictArr.count == 1 || dictArr.count == 0) {
                selectIndex_old = 0;
            }
            [[WordsDictData shareSingle] setDict_Lang:firstLang];
            [lable_keyWords changeTextStyle:FieldLabelStyle_TianZiGe];
            _webView.hidden = YES;
            scrollView.hidden = NO;
        }
    }
    //处理按钮图片 语言
    if (langControl) {
        [langControl removeAllSegments];
        if (dictArr.count == 0 && !isHasHans) {
            langControl.hidden = YES;
        }else if (dictArr.count == 0 && isHasHans){
            langControl.hidden = YES;
            _webView.hidden = NO;
            scrollView.hidden = YES;
            [lable_keyWords changeTextStyle:FieldLabelStyle_Border];
            [langControl insertSegmentWithTitle:@"汉字通" atIndex:0 animated:NO];
        }else if (dictArr.count == 1 && isHasHans){
            langControl.hidden = NO;
            NSDictionary* dic = [dictArr firstObject];
            if ([@"kr" isEqualToString:[dic objectForKey:@"type"]]) {
                [langControl insertSegmentWithTitle:@"汉 / 한" atIndex:0 animated:NO];
            }else if ([@"cn" isEqualToString:[dic objectForKey:@"type"]]){
                [langControl insertSegmentWithTitle:@"汉 / 汉" atIndex:0 animated:NO];
            }else if ([@"en" isEqualToString:[dic objectForKey:@"type"]]){
                [langControl insertSegmentWithTitle:@"汉 / En" atIndex:0 animated:NO];
            }
            
            [langControl insertSegmentWithTitle:@"汉字通" atIndex:1 animated:NO];
        }else if (dictArr.count == 1 && !isHasHans){
            langControl.hidden = YES;
            _webView.hidden = YES;
            scrollView.hidden = NO;
            NSDictionary* dic = [dictArr firstObject];
            if ([@"kr" isEqualToString:[dic objectForKey:@"type"]]) {
                [langControl insertSegmentWithTitle:@"汉 / 한" atIndex:0 animated:NO];
            }else if ([@"cn" isEqualToString:[dic objectForKey:@"type"]]){
                [langControl insertSegmentWithTitle:@"汉 / 汉" atIndex:0 animated:NO];
            }else if ([@"en" isEqualToString:[dic objectForKey:@"type"]]){
                [langControl insertSegmentWithTitle:@"汉 / En" atIndex:0 animated:NO];
            }
        }else if(dictArr.count >= 2){
            langControl.hidden = NO;
            if (dictArr.count >0) {
                for (int i=0; i<dictArr.count; i++) {
                    NSDictionary* dic = [dictArr objectAtIndex:i];
                    nullToNil(dic);
                    if ([@"kr" isEqualToString:[dic objectForKey:@"type"]]) {
                        [langControl insertSegmentWithTitle:@"汉 / 한" atIndex:i animated:NO];
                    }else if ([@"cn" isEqualToString:[dic objectForKey:@"type"]]){
                        [langControl insertSegmentWithTitle:@"汉 / 汉" atIndex:i animated:NO];
                    }else if ([@"en" isEqualToString:[dic objectForKey:@"type"]]){
                        [langControl insertSegmentWithTitle:@"汉 / En" atIndex:0 animated:NO];
                    }
                }
            }
            if (isHasHans) {
                [langControl insertSegmentWithTitle:@"汉字通" atIndex:dictArr.count animated:NO];
            }
        }
    }
    langControl.selectedSegmentIndex = selectIndex_old;
    if (dictArr.count == 1 && !isHasHans) {
        langControl.hidden = YES;
        return 0;
    }
    langControl.dictArr = dictArr;
    //
    NSString* slang = [WordsDictData shareSingle].getDict_Lang;
    NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
    if (!countryCode) {
        countryCode = @"cn";
    }
    if ([@"cn" isEqualToString:slang]) {//选择 右边 汉汉的位置
        countryCode = countryCode.lowercaseString;
        if ([countryCode isEqualToString:@"kr"]
            || [countryCode isEqualToString:@"kp"]
            || [countryCode isEqualToString:@"kor"]
            || [countryCode isEqualToString:@"prk"]) {
            slang = @"kr";
            if (dictArr.count >0) {
                for (int i=0; i<dictArr.count; i++) {
                    NSDictionary* dic = [dictArr objectAtIndex:i];
                    nullToNil(dic);
                    if ([slang isEqualToString:[dic objectForKey:@"type"]]) {
                        return i;
                    }
                }
            }
        }
    }
    //
    if (self.enBook_Dic) {
        slang = @"cn";
    }
    if (dictArr.count >0) {
        for (int i=0; i<dictArr.count; i++) {
            NSDictionary* dic = [dictArr objectAtIndex:i];
            nullToNil(dic);
            if ([slang isEqualToString:[dic objectForKey:@"type"]]) {
                return i;
            }
        }
    }
    //
    return -1;
}
//判断本次取词和上次取词的选项是否一致
-(BOOL)isEqualToLastControlSegmentWithDictArr:(NSArray*)currentDictArr{
    if (langControl.dictArr.count != currentDictArr.count) {
        return NO;
    }else{
        for (int i = 0; i < currentDictArr.count; i++) {
            NSDictionary* lastDict = langControl.dictArr[i];
            NSDictionary* currentDict = currentDictArr[i];
            if (![lastDict[@"type"] isEqualToString:currentDict[@"type"]]) {
                return NO;
            }
        }
    }
    return YES;
}
//获取所有的取词选项
-(NSArray*)getAllLangKeyWithDictArr:(NSArray*)dictArr{
    NSMutableArray* keyArr = [NSMutableArray new];
    for (NSDictionary* dict in dictArr) {
        [keyArr addObject:dict[@"type"]];
    }
    return keyArr;
}
- (void)updateWordsWithDict:(NSDictionary *)dict forWords:(NSString *)word andPinyin:(NSString *)py_n
{
    NSString* keyWords = lable_keyWords.text;
    lable_keyWords.userInteractionEnabled = ([self isStrokeFilesOK]  && [DataProcessing haveChinesWords:keyWords]);
    if (!self.enBook_Dic) {
        if (keyWords && notNULL(keyWords) && (![keyWords isEqualToString:word] || ![py_number isEqualToString:py_n])) {
            return;
        }
    }else{
        if (keyWords && notNULL(keyWords) && (![word isEqualToString:keyWords])) {
            return;
        }
    }
    //
    tempDict = dict;
    tempWord = word;
    tempPinYin = py_n;
    //
    NSArray* views = scrollView.subviews;
    for (UIView* view in views) {
        if(![view isKindOfClass:[UIImageView class]])[view removeFromSuperview];
    }
    //生词声音
    soundArr = [dict objectForKey:@"duyin"];
    nullToNil(soundArr);
    //
    NSString* pinyinStr = [[[[[dict valueForKey:@"dicts"] firstObject] valueForKey:@"items"] firstObject] objectForKey:@"pin_yin"];
    pinyinArr = [pinyinStr componentsSeparatedByString:@" "];
    //笔顺关闭
    [fieldView unshow];
    //
    CGFloat ratio_w = [DataProcessing shareSingle].ratio_w;
    CGFloat pod_forSound = 10/ratio_w;
    CGSize size = [lable_keyWords contentSize];
    CGFloat soudWH = lineHeight_KeyWords+pod_forSound*2;
    CGRect frame = CGRectMake(lable_keyWords.frame.origin.x+size.width+10/[DataProcessing shareSingle].ratio_w-pod_forSound,lable_keyWords.frame.origin.y+size.height*0.5-soudWH*0.5,soudWH,soudWH);
    if(!soundBtn){
        soundBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"" imageOff:@""];
        [soundBtn setDisAbleImageStr:@""];
        NSArray* arr = [NSArray arrayWithObjects:[UIImage imageNamed:@"getWord_btn_speaker_normal.png"],[UIImage imageNamed:@"getWord_btn_speaker_normal_1.png"], nil];
        [soundBtn setAni_UImageArr:arr ani_duration:0.5 forStatus:YES];
        arr = [NSArray arrayWithObjects:[UIImage imageNamed:@"getWord_btn_speaker_normal_1.png"], nil];
        [soundBtn setAni_UImageArr:arr ani_duration:0.5 forStatus:NO];
        soundBtn.delegate = self;
        frame = CGRectMake(pod_forSound,pod_forSound, lineHeight_KeyWords, lineHeight_KeyWords);
        [soundBtn setImageViewFrame:frame];
        [soundBtn setDisAble:YES];
        [soundBtn setHidden:YES];
        [self addSubview:soundBtn];
    }else{
        soundBtn.center = CGPointMake(frame.origin.x+frame.size.width/2, frame.origin.y+frame.size.height/2);
    }
    //
    //刷新真实Word
    NSString* word_net = dict[@"word"];
    if (word_net) {
        [self setKeyWords:word_net andPy_number:py_n];
        lable_keyWords.realWords = word;
    }
    
    //内容
    CGFloat w = scrollView.bounds.size.width-2;
    CGFloat h = scrollView.bounds.size.height;
    CGFloat f_pod = lineHeight_content;
    CGFloat l_pod = lineHeight_content*0.1;
    CGFloat peitu_h = w*3/4;
    CGFloat y = 6/ratio_w;
    NSArray* dictArr = [dict objectForKey:@"dicts"];
    nullToNil(dictArr);
    NSInteger count = dictArr.count;
    if (count>1) count = 1;
    //for (int i =0; i< count; i++)
    int i = [self indexForSwitch:dictArr];
    if(count>0 && i >=0)
    {
        NSDictionary* dic = [dictArr objectAtIndex:i];
        nullToNil(dic);
        //NSString* dicName = [dic objectForKey:@"name"];
        //nullToNil(dicName);
        
        //字典 容器view
        frame = CGRectMake(0, y, w, 0);
        UIView* view = [[UIView alloc] initWithFrame:frame];
        view.backgroundColor = [UIColor clearColor];
        [scrollView addSubview:view];
        
        //字典内容 //英文书
        if (self.enBook_Dic) {
            //音标
            NSString* yinbiao = dic[@"yin_biao"];
            nullToNil(yinbiao);
            frame = CGRectMake(0, y, w, lineHeight_PinyinWords);
            UILabel* lable_yb = [[UILabel alloc] initWithFrame:frame];
            lable_yb.font = [UIFont fontWithName:__SpeakerEnglishFontName size:lineHeight_PinyinWords*0.9];
            lable_yb.textColor = [UIColor blackColor];
            [view addSubview:lable_yb];
            lable_yb.text = yinbiao;
            y += frame.size.height*1.5;
            
            //词性
            NSArray* dictArr = [dic objectForKey:@"ci_xing"];
            nullToNil(dictArr);
            for (NSDictionary* dicItems in dictArr) {
                
                //词性
                NSString* cx = dicItems[@"cx"];
                NSString* fu_shu = dicItems[@"fu_shu"];
                nullToNil(cx);
                nullToNil(fu_shu);
                frame = CGRectMake(0, y, w, lineHeight_PinyinWords);
                UILabel* lable_cxfs = [[UILabel alloc] initWithFrame:frame];
                lable_cxfs.font = [UIFont systemFontOfSize:lineHeight_PinyinWords];
                lable_cxfs.textColor = __baseHighLineColer;
                [view addSubview:lable_cxfs];
                lable_cxfs.text = [NSString stringWithFormat:@"%@ %@",cx,fu_shu];
                y += frame.size.height*1.5;
                
                //解释
                NSArray* jieshi = [dicItems objectForKey:@"jie_shi"];
                nullToNil(jieshi);
                for (NSDictionary* jsDict in jieshi) {
                    //解释
                    NSString* jstr = [jsDict objectForKey:@"js"];
                    nullToNil(jstr);
                    if (jstr && jstr.length > 0) {
                        frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                        UILabel* label = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:label];
                        label.text = jstr;
                        label.textColor = __baseHighLineColer;
                        label.font = [UIFont systemFontOfSize:lineHeight_content*0.8];
                        [label resizeToFit];
                        //
                        frame = CGRectMake(0, y, w, lineHeight_content);
                        UILabel* lb = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:lb];
                        lb.text = @"·";//@"☞";
                        lb.textColor = [UIColor blackColor];
                        lb.font = [UIFont systemFontOfSize:lineHeight_content*0.8];
                        [lb resizeToFit];
                        //
                        y += label.frame.size.height+l_pod;
                    }
                    //例句
                    NSArray* liju = [jsDict objectForKey:@"li_ju"];
                    nullToNil(liju);
                    for (NSDictionary* lijuDict in liju) {
                        NSString* chs = [lijuDict objectForKey:@"lj"];
                        nullToNil(chs);
                        if (chs && chs.length > 0) {
                            frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                            UILabel* label = [[UILabel alloc] initWithFrame:frame];
                            [view addSubview:label];
                            label.text = chs;
                            label.textColor = [UIColor blackColor];
                            label.font = [UIFont systemFontOfSize:lineHeight_content*0.78];
                            [label resizeToFit];
                            y += label.frame.size.height;
                        }
                        NSString* eng = [lijuDict objectForKey:@"lj_js"];
                        nullToNil(eng);
                        if (eng && eng.length > 0) {
                            frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                            UILabel* label = [[UILabel alloc] initWithFrame:frame];
                            [view addSubview:label];
                            label.text = eng;
                            label.textColor = [UIColor grayColor];
                            label.font = [UIFont systemFontOfSize:lineHeight_content*0.78];
                            [label resizeToFit];
                            y += label.frame.size.height;
                        }
                        y += l_pod;
                    }
                }
                y += l_pod*12;
            }
        }
        
        
        //字典内容 //中文书
        NSArray* dictArr = [dic objectForKey:@"items"];
        nullToNil(dictArr);
        for (NSDictionary* dicItems in dictArr) {
            //
            //拼音
            frame = CGRectMake(0, y, w, lineHeight_PinyinWords);
            UILabel* lable_Pinyin = [[UILabel alloc] initWithFrame:frame];
            lable_Pinyin.font = [UIFont fontWithName:__PinYinFontName size:lineHeight_PinyinWords*0.88];
            lable_Pinyin.textColor = [UIColor blackColor];
            [view addSubview:lable_Pinyin];
            NSString* py = [dicItems objectForKey:@"pin_yin"];
            nullToNil(py);
            lable_Pinyin.text = [HansPinYin convertToPinyinTTF_withPinyinNumber:py].pinyin_ttf;
            y += frame.size.height*1.5;
            
            //配图
            NSArray* peitu = [dicItems objectForKey:@"pei_tu"];
            nullToNil(peitu);
            for (NSString* str in peitu) {
                if(str.length==0)continue;
                frame = CGRectMake(0, y, w, peitu_h);
                UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
                imgv.contentMode = UIViewContentModeScaleAspectFit;
                [imgv JRSD_setImageWithURL:[NSURL URLWithString:[DataProcessing fullPeituUrl:str]] placeholderImage:nil options:JRSDWebImageRefreshCached];
                [view addSubview:imgv];
                y += frame.size.height;
            }
            
            //解释
            NSArray* jieshi = [dicItems objectForKey:@"jie_shi"];
            nullToNil(jieshi);
            for (NSDictionary* jsDict in jieshi) {
                //解释
                NSString* jstr = [jsDict objectForKey:@"str"];
                nullToNil(jstr);
                if (jstr && jstr.length > 0) {
                    frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                    UILabel* label = [[UILabel alloc] initWithFrame:frame];
                    [view addSubview:label];
                    label.text = jstr;
                    label.textColor = __baseHighLineColer;
                    label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                    [label resizeToFit];
                    //
                    frame = CGRectMake(0, y, w, lineHeight_content);
                    UILabel* lb = [[UILabel alloc] initWithFrame:frame];
                    [view addSubview:lb];
                    lb.text = @"·";//@"☞";
                    lb.textColor = [UIColor blackColor];
                    lb.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                    [lb resizeToFit];
                    //
                    y += label.frame.size.height+l_pod;
                }
                //短语
                NSArray* duanyu = [jsDict objectForKey:@"duan_yu"];
                nullToNil(duanyu);
                for (NSDictionary* dyDict in duanyu) {
                    NSString* chs = [dyDict objectForKey:@"chs"];
                    nullToNil(chs);
                    if (chs && chs.length > 0) {
                        frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                        UILabel* label = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:label];
                        label.text = chs;
                        label.textColor = [UIColor blackColor];
                        label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                        [label resizeToFit];
                        y += label.frame.size.height;
                    }
                    NSString* eng = [dyDict objectForKey:@"eng"];
                    nullToNil(eng);
                    if (eng && eng.length > 0) {
                        frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                        UILabel* label = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:label];
                        label.text = eng;
                        label.textColor = [UIColor grayColor];
                        label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                        [label resizeToFit];
                        y += label.frame.size.height;
                    }
                    y += l_pod;
                }
                //例句
                NSArray* liju = [jsDict objectForKey:@"li_ju"];
                nullToNil(liju);
                for (NSDictionary* lijuDict in liju) {
                    NSString* chs = [lijuDict objectForKey:@"chs"];
                    nullToNil(chs);
                    if (chs && chs.length > 0) {
                        //替换~
                        NSMutableAttributedString* (^replaceTheWord)(NSString*,NSString*) = ^(NSString* theStr, NSString* keyStr){
                            if (theStr == nil)theStr = @"";
                            if (keyStr == nil)return [[NSMutableAttributedString alloc] initWithString:theStr];
                            NSMutableAttributedString* mastr = [[NSMutableAttributedString alloc] initWithString:[theStr stringByReplacingOccurrencesOfString:@"~" withString:keyStr]];
                            NSInteger len = theStr.length;
                            NSMutableArray* smarr = [NSMutableArray new];
                            for (int si = 0; si < len; si++) {
                                if ([theStr characterAtIndex:si] == '~') {
                                    NSRange range = NSMakeRange((keyStr.length-1)*smarr.count+si, keyStr.length);
                                    [smarr addObject:[NSValue valueWithRange:range]];
                                    [mastr addAttribute:NSForegroundColorAttributeName
                                                  value:[UIColor colorWithHexString:@"#ff863b"]
                                                  range:range];
                                }
                            }
                            return mastr;
                        };
                        
                        //chs = [chs stringByReplacingOccurrencesOfString:@"~" withString:lable_keyWords.text];
                        NSAttributedString* attrStr = replaceTheWord(chs,lable_keyWords.text);
                        //
                        frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                        UILabel* label = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:label];
                        label.text = attrStr.string;
                        label.textColor = [UIColor blackColor];
                        label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                        [label resizeToFit];
                        y += label.frame.size.height;
                        //
                        //替换~
                        label.attributedText = attrStr;
                    }
                    NSString* eng = [lijuDict objectForKey:@"eng"];
                    nullToNil(eng);
                    if (eng && eng.length > 0) {
                        frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
                        UILabel* label = [[UILabel alloc] initWithFrame:frame];
                        [view addSubview:label];
                        label.text = eng;
                        label.textColor = [UIColor grayColor];
                        label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
                        [label resizeToFit];
                        y += label.frame.size.height;
                    }
                    y += l_pod;
                }
            }

//            //反义词
//            NSArray* fanyici = [dicItems objectForKey:@"fan_yi_ci"];
//            nullToNil(fanyici);
//            for (NSDictionary* fycDict in fanyici) {
//                NSString* chs = [fycDict objectForKey:@"chs"];
//                nullToNil(chs);
//                if (chs && chs.length > 0) {
//                    frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
//                    UILabel* label = [[UILabel alloc] initWithFrame:frame];
//                    [view addSubview:label];
//                    label.text = chs;
//                    label.textColor = [UIColor blackColor];
//                    label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
//                    [label resizeToFit];
//                    y += label.frame.size.height;
//                }
//                NSString* eng = [fycDict objectForKey:@"eng"];
//                nullToNil(eng);
//                if (eng && eng.length > 0) {
//                    frame = CGRectMake(f_pod, y, w-f_pod, lineHeight_content);
//                    UILabel* label = [[UILabel alloc] initWithFrame:frame];
//                    [view addSubview:label];
//                    label.text = eng;
//                    label.textColor = [UIColor grayColor];
//                    label.font = [UIFont systemFontOfSize:lineHeight_content*0.9];
//                    [label resizeToFit];
//                    y += label.frame.size.height;
//                }
//            }
        }
    }
    h += 10;
    y = y>=h ? y : h;
    [scrollView setContentSize:CGSizeMake(w, y)];
    //
    if (_webView.hidden == NO) {
        [self loadWordDictHtmlWithWord:[word substringToIndex:1]];
        [lable_keyWords changeTextStyle:FieldLabelStyle_Border];
    }
}

- (void)addWaittingView
{
    UIActivityIndicatorView* loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loading.center = CGPointMake(scrollView.frame.size.width/2, scrollView.frame.size.height/2);
    [loading startAnimating];
    [scrollView addSubview:loading];
    //
    loading.translatesAutoresizingMaskIntoConstraints = NO;
    [loading lyt_centerInParent];
}

-(void)loadNoHansHtml{
    _webView.web_word = nil;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"getword.bundle/noHansRemind" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [_webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}


- (void)clean
{
    [noteBtn setDisAble:YES];
    [biShunBtn setDisAble:YES];
    [soundBtn setDisAble:YES];
    [soundBtn setHidden:YES];
    //
    NSArray* views = scrollView.subviews;
    for (UIView* view in views) {
        if(![view isKindOfClass:[UIImageView class]])[view removeFromSuperview];
    }
    [scrollView setContentSize:CGSizeMake(0, 0)];
    //
//    lable_PinyinWords.text = nil;
    lable_keyWords.text = nil;
    py_number = nil;
    soundArr = nil;
    self.pt_unshowFollowView = nil;
    //
    tempDict = nil;
    tempWord = nil;
    tempPinYin = nil;
    //隐藏语言按钮
    langControl.hidden = YES;
    //清空webView网页数据
    _webView.web_word = nil;
    [_webView loadHTMLString:@" " baseURL:nil];
}

- (void)setKeyWords:(NSString *)str andPy_number:(NSString*)py_n
{
    lable_keyWords.text = str;
    lable_keyWords.realWords = str;
    py_number = py_n;
    //
    if (lable_keyWords && soundBtn) {
        CGSize size = [lable_keyWords contentSize];
        CGRect frame = soundBtn.frame;
        frame.origin.x = lable_keyWords.frame.origin.x+size.width+15/[DataProcessing shareSingle].ratio_w;
        soundBtn.center = CGPointMake(frame.origin.x+frame.size.width/2, frame.origin.y+frame.size.height/2);
    }
    //笔顺关闭
    [fieldView unshow];
}

- (void)setSoundReady_forWords:(NSString *)word andPinyin:(NSString *)py_n
{
    NSString* keyWords = lable_keyWords.realWords;
    if (keyWords && (![keyWords isEqualToString:word] || ![py_number isEqualToString:py_n])) {
        return;
    }
    //
    [soundBtn setHidden:NO];
    [soundBtn setButtonStatus:NO];
    [soundBtn setDisAble:NO];
}

- (void)show
{
    if (isTransformWorking) {
        return;
    }
    isTransformWorking = YES;
    BOOL isModal_OK = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
    if (isModal_OK && self.pt_unshowFollowView && self.pt_unshowFollowView.superview) {
        self.pt_unshow = [self.pt_unshowFollowView.superview convertPoint:self.pt_unshowFollowView.center toView:nil];
    }
    self.center = self.pt_unshow;
    [UIView animateWithDuration:0.5 animations:^{
        self.transform = CGAffineTransformMakeScale(1, 1);
        self.hidden = NO;
        self.center = self.pt_show;
    }completion:^(BOOL finished) {
        isTransformWorking = NO;
    }];
}

- (void)unShow
{
    if (isTransformWorking) {
        return;
    }
    [self unShow_must];
}

- (void)unShow_must
{
    isTransformWorking = YES;
    [fieldView unshow];
    BOOL isModal_OK = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
    if (isModal_OK && self.pt_unshowFollowView && self.pt_unshowFollowView.superview) {
        self.pt_unshow = [self.pt_unshowFollowView.superview convertPoint:self.pt_unshowFollowView.center toView:nil];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.transform = CGAffineTransformMakeScale(0.000001, 0.000001);
        self.hidden = NO;
        self.center = self.pt_unshow;
    }completion:^(BOOL finished) {
        self.hidden = YES;
        isTransformWorking = NO;
        [self clean];
    }];
}

//选择切换语言/汉字通
-(void)tapLangControlAction:(UISegmentedControl*)control{
    if (tempWord) {
        NSString* selectTitle = [control titleForSegmentAtIndex:control.selectedSegmentIndex];
        if ([@"汉 / 汉" isEqualToString:selectTitle] || [@"汉 / 한" isEqualToString:selectTitle]) {
            _webView.hidden = YES;
            scrollView.hidden = NO;
            [lable_keyWords changeTextStyle:FieldLabelStyle_TianZiGe];
            [[WordsDictData shareSingle] setDict_Lang:@"cn"];
        }else if([@"汉 / En" isEqualToString:selectTitle]){
            _webView.hidden = YES;
            scrollView.hidden = NO;
            [lable_keyWords changeTextStyle:FieldLabelStyle_TianZiGe];
            [[WordsDictData shareSingle] setDict_Lang:@"en"];
        }else if ([@"汉字通" isEqualToString:selectTitle]){
            //
            lable_keyWords.userInteractionEnabled = YES;
            //笔顺关闭
            [fieldView unshow];
            _webView.hidden = NO;
            scrollView.hidden = YES;
            [lable_keyWords changeTextStyle:FieldLabelStyle_Border];
            [self loadWordDictHtmlWithWord:[lable_keyWords.text substringToIndex:1]];
        }
        if (![@"汉字通" isEqualToString:selectTitle]) {
            [self updateWordsWithDict:tempDict forWords:tempWord andPinyin:tempPinYin];
        }
        [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[RE_main,@"取词_切换词典"] needReturnValue:NO];
    }
}
//加载汉字通网页
-(void)loadWordDictHtmlWithWord:(NSString*)word{
    
    
    if (![wordsDict objectForKey:word]) {
        [self loadNoHansHtml];
        return;
    }
    if (!webIsLoadFinish || ![_webView.web_word isEqualToString:word]) {
        NSString* urlStr = [DataProcessing fullWordDictUrl:wordsDict[word] ContainMp3Path:[self getTextPinyinWithWord:word]];
#if __Debug_JSLog
        NSInteger htmlArc = arc4random() % 100;
        urlStr = [NSString stringWithFormat:@"%@&%@=%@",urlStr,@(htmlArc),@(htmlArc)];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
#else
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
#endif
        [[RNCachingURLProtoclSetting getInstance] addURLForCaching:urlStr outTime:[DataProcessing shareSingle].dictExpiry_Date autoOutTimeDays:[DataProcessing shareSingle].dictExpiry_Day];//telen 缓存设置 0实时刷新
        [_webView loadRequest:request];
        _webView.web_word = word;
    }
}

-(NSString*)getTextPinyinWithWord:(NSString*)word{
    NSString* wordPinyin = nil;
    NSString* showingText = lable_keyWords.text;
    if (pinyinArr.count == showingText.length) {
        for (int i = 0; i < showingText.length; i ++) {
            NSString* oneWord = [showingText substringWithRange:NSMakeRange(i, 1)];
            if ([oneWord isEqualToString:word]) {
                wordPinyin = pinyinArr[i];
                break;
            }
        }
    }
    return wordPinyin;
}

#pragma mark - WebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self addWebWaittingView];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self removeWebWaittingView];
    webIsLoadFinish = YES;
    NSString* txt = webView.web_word;
    if (txt) {
        [self msgTo_menthed:@"statistical_hztshow:" refs:@[txt] needReturnValue:NO];
    }
}

-(void)addWebWaittingView{
    if (!webWaittingView) {
        UIView* waittingView = [[UIView alloc] init];
        waittingView.backgroundColor = [UIColor whiteColor];
        [_webView addSubview:waittingView];
        [waittingView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
            make.edges.JRMAS_equalTo(_webView);
        }];
        UIActivityIndicatorView* loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        loading.center = CGPointMake(_webView.frame.size.width/2, _webView.frame.size.height/2);
        [loading startAnimating];
        [waittingView addSubview:loading];
        //
        loading.translatesAutoresizingMaskIntoConstraints = NO;
        [loading lyt_centerInParent];
        webWaittingView = waittingView;
    }
}
-(void)removeWebWaittingView{
    if (webWaittingView) {
        [webWaittingView removeFromSuperview],webWaittingView = nil;
    }
}
#pragma mark - StatusButton_2_ViewDelegate
- (void)statusButton_2_View_didClicked:(StatusButton_2_View *)sbview
{
    if (sbview == soundBtn)[soundBtn setButtonStatus:!soundBtn.onOff];
    if (sbview == soundBtn && !soundBtn.onOff) {
        [[WordsDictData shareSingle] playSounds:soundArr withSign:py_number];
        //telen 统计
//        [UMSAgent postEvent:@"Page_getword_clk_speaker" label:[NSString stringWithFormat:@"%@_%@",self.bookName,lable_keyWords.text]];
//        
//        //阅读统计
//        [[DBHelper shareInstance] addReadInfo_pageWord:_currentBookId pageIndex:_currentPage_C type:RType_audio word:lable_keyWords.realWords];
        [self msgTo_menthed:@"statistical_soundplay" refs:nil needReturnValue:NO];
    }
    //
//    if (sbview == langBtn){
//        if (tempWord) {
//            if (!langBtn.onOff) {
//                [[WordsDictData shareSingle] setDict_Lang:@"cn"];
//            }else{
//                [[WordsDictData shareSingle] setDict_Lang:@"en"];
//            }
//            [self updateWordsWithDict:tempDict forWords:tempWord andPinyin:tempPinYin];
//            
//            [NSObject msgToClassName:@"TLMobStat" menthed:@"logEvent:eventLabel:" refs:@[RE_main,@"取词_切换词典"] needReturnValue:NO];
//        }
//    }
    //
}

- (void)wordsDictData_DidStartPlaySounds:(NSArray *)soundArr withSign:(NSString *)sign
{
    if ([sign isEqualToString:py_number]) {
        [soundBtn setButtonStatus:YES];
    }
}

- (void)wordsDictData_DidFinishPlaySounds:(NSArray *)soundArr withSign:(NSString *)sign
{
    if ([sign isEqualToString:py_number]) {
        [soundBtn setButtonStatus:NO];
    }
}

@end


#pragma mark- 带田字格的Label

@implementation CNOneFieldLabel

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        frame.origin = CGPointZero;
        //
        self.imgv = [[UIImageView alloc] initWithFrame:frame];
        _imgv.image = [UIImage imageNamed:@"getword_tianzige.png"];
        [self addSubview:_imgv];
        //
        UILabel* label = [[UILabel alloc] initWithFrame:frame];
        _textlabel = label;
        [self addSubview:label];
        //
        self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = frame;
        _btn.backgroundColor = [UIColor clearColor];
        [self addSubview:_btn];
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    frame.origin = CGPointZero;
    _imgv.frame = _textlabel.frame = _btn.frame = frame;
}

- (void)setDelegate:(CNFieldLabel *)delegate
{
    _delegate = delegate;
    [_btn addTarget:self action:@selector(didclickBtn) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didclickBtn
{
    if (_delegate && [_delegate respondsToSelector:@selector(didClickOnWord:)]) {
        [_delegate didClickOnWord:_textlabel.text];
    }
}

- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled
{
    [super setUserInteractionEnabled:userInteractionEnabled];
    _btn.enabled = userInteractionEnabled;
    _imgv.hidden = !userInteractionEnabled;
}

@end

@implementation CNFieldLabel

- (void)dealloc
{
    self.text = nil;
    self.textColor = nil;
    self.font = nil;
#if __Debug_is_dealloced_log_2
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        oneFoielLabelArr = [[NSMutableArray alloc] initWithCapacity:0];
        _cnFiedWeightHeight = 60;
        _fieldPod = 5;
        //
        [self addScorllView];
    }
    return self;
}

-(void)addScorllView{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.scrollView];
}

- (void)setText:(NSString *)text
{
    _text = text;
    NSInteger count = text.length;
    self.scrollView.contentSize = CGSizeMake(count * (_cnFiedWeightHeight + _fieldPod), 0);
    BOOL hasChinese = [DataProcessing haveChinesWords:text];
    if (hasChinese) {
        while (count<oneFoielLabelArr.count) {
            CNOneFieldLabel* olabel = [oneFoielLabelArr lastObject];
            [olabel removeFromSuperview];
            [oneFoielLabelArr removeObject:olabel];
        }
        for (int i =0; i<count; i++) {
            NSString* word = [text substringWithRange:NSMakeRange(i, 1)];
            if (i < oneFoielLabelArr.count) {
                CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
                olabel.frame = CGRectMake(i*_cnFiedWeightHeight  + _fieldPod * i, 0, _cnFiedWeightHeight-_fieldPod, _cnFiedWeightHeight-_fieldPod);
                olabel.textlabel.text = word;
                if (![DataProcess onlyChinesWords:word]) {
                    olabel.userInteractionEnabled = NO;
                }else{
                    olabel.userInteractionEnabled = self.userInteractionEnabled;
                }
            }else{
                CNOneFieldLabel* olabel = [[CNOneFieldLabel alloc] initWithFrame:CGRectMake(i*_cnFiedWeightHeight + _fieldPod * i, 0, _cnFiedWeightHeight-_fieldPod, _cnFiedWeightHeight-_fieldPod)];
                olabel.textlabel.textAlignment = NSTextAlignmentCenter;
                olabel.delegate = self;
                olabel.textlabel.text = word;
                if (![DataProcess onlyChinesWords:word]) {
                    olabel.userInteractionEnabled = NO;
                }else{
                    olabel.userInteractionEnabled = self.userInteractionEnabled;
                }
                if(_font)olabel.textlabel.font = _font;
                if(_textColor)olabel.textlabel.textColor = _textColor;
                [self.scrollView addSubview:olabel];
                [oneFoielLabelArr addObject:olabel];
            }
        }
    }else{
        while (0<oneFoielLabelArr.count) {
            CNOneFieldLabel* olabel = [oneFoielLabelArr lastObject];
            [olabel removeFromSuperview];
            [oneFoielLabelArr removeObject:olabel];
        }
        if (text && text.length > 0) {
            //
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _cnFiedWeightHeight*7, _cnFiedWeightHeight-_fieldPod)];
            label.text = text;
            label.font = _font;
            CGSize size = label.contentSize;
            size.width = ceil(size.width);
            //
            CNOneFieldLabel* olabel = [[CNOneFieldLabel alloc] initWithFrame:CGRectMake(0, 0, size.width, _cnFiedWeightHeight-_fieldPod)];
            olabel.textlabel.textAlignment = NSTextAlignmentCenter;
            olabel.textlabel.text = text;
            olabel.userInteractionEnabled = self.userInteractionEnabled;
            if(_font)olabel.textlabel.font = _font;
            if(_textColor)olabel.textlabel.textColor = _textColor;
            [self.scrollView addSubview:olabel];
            [oneFoielLabelArr addObject:olabel];
            [olabel setUserInteractionEnabled:NO];
        }
    }
}

//- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled
//{
//    [super setUserInteractionEnabled:userInteractionEnabled];
//    for (int i =0; i<oneFoielLabelArr.count; i++) {
//        CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
//        olabel.userInteractionEnabled = userInteractionEnabled;
//    }
//}

- (void)setTextColor:(UIColor *)textColor
{
    _textColor = textColor;
    for (int i =0; i<oneFoielLabelArr.count; i++) {
        CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
        olabel.textlabel.textColor = textColor;
    }
}

- (void)setFont:(UIFont *)font
{
    _font = font;
    for (int i =0; i<oneFoielLabelArr.count; i++) {
        CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
        olabel.textlabel.font = font;
    }
}

- (void)setCnFiedWeightHeight:(NSUInteger)cnFiedWeightHeight
{
    _cnFiedWeightHeight = cnFiedWeightHeight;
    for (int i =0; i<oneFoielLabelArr.count; i++) {
        CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
        [olabel setFrame:CGRectMake(i*_cnFiedWeightHeight, 0, _cnFiedWeightHeight-_fieldPod, _cnFiedWeightHeight-_fieldPod)];
    }
}

- (void)setFieldPod:(NSInteger)fieldPod
{
    _fieldPod = fieldPod;
    for (int i =0; i<oneFoielLabelArr.count; i++) {
        CNOneFieldLabel* olabel = [oneFoielLabelArr objectAtIndex:i];
        [olabel setFrame:CGRectMake(i*_cnFiedWeightHeight, 0, _cnFiedWeightHeight-_fieldPod, _cnFiedWeightHeight-_fieldPod)];
    }
}

- (void)didClickOnWord:(NSString *)text
{
    //border情况下,点击字变化边框颜色
    if (_fieldLabelStyle == FieldLabelStyle_Border) {
        for (CNOneFieldLabel* olabel in oneFoielLabelArr) {
            if (olabel.textlabel.text == text) {
                olabel.layer.borderColor = [UIColor colorWithHexString:@"#7E8FDA"].CGColor;
                olabel.textlabel.textColor = [UIColor colorWithHexString:@"#7E8FDA"];
                olabel.layer.borderWidth = 1;
            }else{
                olabel.layer.borderColor = [UIColor colorWithHexString:@"#BDBDBD"].CGColor;
                olabel.textlabel.textColor = [UIColor colorWithHexString:@"#4A4A4A"];
                olabel.layer.borderWidth = 1;
            }
        }
    }
    //
    if (_delegate && [_delegate respondsToSelector:@selector(didClickOnWord:)]) {
        [_delegate didClickOnWord:text];
    }
}

- (CGSize)contentSize
{
    CGFloat w = 0;
    for (CNOneFieldLabel* olabel in oneFoielLabelArr) {
        w += olabel.frame.size.width+_fieldPod;
        if (w >= self.frame.size.width) {
            return CGSizeMake(self.frame.size.width, _cnFiedWeightHeight);
        }
    }
    return CGSizeMake(w, _cnFiedWeightHeight);
}

- (void)changeTextStyle:(FieldLabelStyle)fieldLabelStyle{
    _fieldLabelStyle = fieldLabelStyle;
    if (fieldLabelStyle == FieldLabelStyle_TianZiGe) {
        for (CNOneFieldLabel* olabel in oneFoielLabelArr) {
            olabel.layer.borderWidth = 0;
            //olabel.imgv.hidden = NO;
            olabel.textlabel.textColor = [UIColor colorWithHexString:@"#7E8FDA"];
            self.userInteractionEnabled = self.userInteractionEnabled;
        }
    }else if(fieldLabelStyle == FieldLabelStyle_Border){
        for (CNOneFieldLabel* olabel in oneFoielLabelArr) {
            NSInteger index = [oneFoielLabelArr indexOfObject:olabel];
            olabel.imgv.hidden = YES;
            if (index == 0) {
                olabel.layer.borderColor = [UIColor colorWithHexString:@"#7E8FDA"].CGColor;
                olabel.textlabel.textColor = [UIColor colorWithHexString:@"#7E8FDA"];
                olabel.layer.borderWidth = 1;
            }else{
                olabel.layer.borderColor = [UIColor colorWithHexString:@"#BDBDBD"].CGColor;
                olabel.textlabel.textColor = [UIColor colorWithHexString:@"#4A4A4A"];
                olabel.layer.borderWidth = olabel.userInteractionEnabled;
            }
        }
    }
}

@end


#pragma mark- 带田字格和功能按钮的View

@implementation CNFieldView
{
    UIButton* rePlayBtn;
}
@synthesize word = word;

- (void)dealloc
{
    self.word = nil;
//#ifndef YDYH_PJ
    if (mContainer != nil) {
        [mContainer close];
        mContainer = nil;
    }
//#endif
#if __Debug_is_dealloced_log_2
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //self.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.6];
        self.backgroundColor = [UIColor whiteColor];
        frameShow = frame;
        frameShow.origin.y += frameShow.size.height;
        frameUnshow = frameShow;
        frameShow = frame;
        //
        CGRect frameStroke = frame;
        CGFloat strokeScale = 1;
        if (frame.size.width<300) {
            frameStroke.size = CGSizeMake(300, 300);
            strokeScale = frame.size.width/300.0;
        }
//#ifndef YDYH_PJ
        UIView* viewSs = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frameStroke.size.width, frameStroke.size.width)];
        UIStrokeView* viewStroke = [[UIStrokeView alloc] initWithFrame:viewSs.bounds];
        if(strokeScale<1)[viewSs setTransform:CGAffineTransformMakeScale(strokeScale, strokeScale)];
        [viewSs addSubview:viewStroke];
        [self addSubview:viewSs];
        viewSs.center = CGPointMake(frame.size.width*0.5, frame.size.width*0.55);
        _viewStroke = viewStroke;
        _viewStroke.maxWidth = _viewStroke.maxHeight = ceil(frameStroke.size.width*0.9);
        _viewStroke.fillContour = YES;
        _viewStroke.drawContour = YES;
        _viewStroke.clrLine = 0xffaaaaaa;
        _viewStroke.clrBuYu = 0xff000000;
        _viewStroke.clrBuShou = 0xff000000;
        _viewStroke.playChnWave = NO;
        NSInteger maxUpdate = 180;
        maxUpdate /= [DataProcessing shareSingle].ratio_w;
        maxUpdate *= [UIScreen mainScreen].scale/2;
        _viewStroke.maxUpdate = maxUpdate;
        [_viewStroke clearShow];

        //
        [self unshow];
        //
        if (mContainer == nil) {
            // to load stroke.db
            //NSString *sPath = [[NSBundle mainBundle] pathForResource:@"stroke" ofType:@"db"];
            NSString* sPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"stroke.db"];
            // fill.db is an optional file for stroke-filling
            NSString *sFill = nil;
            //sFill = [[NSBundle mainBundle] pathForResource:@"fill" ofType:@"db"];
            sFill = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"fill.db"];
            mContainer = [[StrokeViewContainer alloc] initWithStrokeView:self.viewStroke];
            // soundPath may be nil or @"" for root folder
            mContainer.soundPath = @"strokewave";
            NSString* countryCode = [CacheData shareSingle].getUserLoginInfo.country_code;
            if ([@"SG" isEqualToString:countryCode]) {
                sPath = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"sg/stroke.db"];
                sFill = [[DataProcessing shareSingle].supportFilesDirector stringByAppendingPathComponent:@"sg/fill.db"];
            }
            [mContainer initWithDBPath:sPath guidePath:sFill];
        }
//#endif
        //btn
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage* imge = [UIImage imageNamed:@"getword_down.png"];
        CGSize sz = CGSizeMake(imge.size.width*12, imge.size.height*8);
        frame.origin = CGPointZero;
        frame.origin.x += (frame.size.width - sz.width)*0.5;
        frame.origin.y += frame.size.height - sz.height;
        frame.origin.y *= 0.95;
        frame.size = sz;
        btn.frame = frame;
        [btn setImage:imge forState:UIControlStateNormal];
        [self addSubview:btn];
        [btn addTarget:self action:@selector(unshow) forControlEvents:UIControlEventTouchUpInside];
        //btn2
        btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.color_Debug_View = [UIColor greenColor];
//#ifndef YDYH_PJ
        frame= _viewStroke.frame;
        frame.size.height *= strokeScale;
        frame.size.width *= strokeScale;
//#endif
        btn.frame = frame;
        [self addSubview:btn];
        [btn addTarget:self action:@selector(replayStroke) forControlEvents:UIControlEventTouchUpInside];
        rePlayBtn = btn;
    }
    return self;
}

- (void)show
{
    [UIView animateWithDuration:0.3f animations:^{
        self.frame = frameShow;
        _isShow = NO;
    } completion:^(BOOL finished) {
        [self playWord:word];
        _isShow = YES;
    }];
}

- (void)unshow
{
//#ifndef YDYH_PJ
    [_viewStroke stopFilling];
//#endif
    [UIView animateWithDuration:0.3f animations:^{
        self.frame = frameUnshow;
        _isShow = NO;
    } completion:^(BOOL finished) {
//#ifndef YDYH_PJ
        [_viewStroke clearShow];
//#endif
        _isShow = NO;
    }];
}

- (void)replayStroke
{
    [self playWord:word];
}

- (void)_playWord:(NSString*)wd
{
//#ifndef YDYH_PJ
    rePlayBtn.userInteractionEnabled = NO;
    [_viewStroke fillStroke:word withDelegate:mContainer];
    [DataProcessing do_Async:^{
        rePlayBtn.userInteractionEnabled = YES;
    } delay:1];
//#endif
}

- (void)playWord:(NSString *)wd
{
//#ifndef YDYH_PJ
    if (wd && wd.length == 1) {
        word = wd;
        //[_viewStroke stopFilling];
        [_viewStroke clearShow];
        rePlayBtn.userInteractionEnabled = NO;
        [self performSelector:@selector(_playWord:) withObject:wd afterDelay:0.01];
//        [self _playWord:wd];
    }
//#endif
}

@end





